package com.zainzhou.handler;

import com.zainzhou.dao.entity.UserEntity;
import com.zainzhou.dao.repository.UserRepository;
import com.zainzhou.pojo.request.CreateUserRequest;
import com.zainzhou.pojo.request.LoginRequest;
import com.zainzhou.pojo.request.UpdateUserRequest;
import com.zainzhou.pojo.response.LoginResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

/**
 * @author : 周振宇
 * Created on 2024/06/19 11:05
 **/
@Service
public class UserHandler {
    @Resource
    private UserRepository userRepository;

    public LoginResponse login(LoginRequest loginRequest){
        UserEntity user = userRepository.login(loginRequest.getUsername(),passwordMd5(loginRequest.getPassword()));
        if(null != user){
            return LoginResponse.builder()
                    .email(user.getEmail())
                    .username(user.getUserName())
                    .createBy(user.getCreateTime())
                    .createAt(user.getCreateUser())
                    .updateBy(user.getUpdateTime())
                    .updateAt(user.getUpdateUser())
                    .token(user.getId())
                    .loginStatus(true)
                    .build();
        }else{
            return LoginResponse.builder()
                    .loginStatus(false)
                    .build();
        }
    }

    public String createUser(CreateUserRequest request){
        UserEntity entity = UserEntity.builder()
                .id(UUID.randomUUID().toString().replace("-",""))
                .userName(request.getUserName())
                .password(passwordMd5(request.getPassword()))
                .copilotVersion(request.getCopilotVersion())
                .createTime(LocalDateTime.now())
                .createUser("admin")
                .createUserName("admin")
                .updateTime(LocalDateTime.now())
                .updateUser("admin")
                .updateUserName("admin")
                .deleteFlag("0")
                .build();
        return userRepository.createUser(entity) > 0 ? entity.getId() : null;
    }

    public int updateUser(UpdateUserRequest request){
        UserEntity user = userRepository.queryUserById(request.getId());
        if (Objects.isNull(user)){
            return 0;
        }
        user.setUserName(request.getUserName());
        user.setPassword(passwordMd5(request.getPassword()));
        user.setCopilotVersion(request.getCopilotVersion());
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateUser("api");
        user.setUpdateUserName("api");
        return userRepository.updateUser(user);
    }

    public int deleteUser(String id){
        return userRepository.deleteUser(id);
    }

    /**
     * 密码加密
     * @param password 密码明文
     * @return 密码密文
     */
    public String passwordMd5(String password){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
